// word-dictation.js - 单词听写页面
const app = getApp();

Page({
  data: {
    // 仅保留页面级状态，实际听写状态由DictationManager管理
    isLoading: true,
    isDictating: false,
    isSelectingSource: false,
    showDictationResult: false
  },

  onLoad: function(options) {
    // 获取DictationManager实例
    this.dictationManager = app.getDictationManager();
    
    // 重置状态到初始值，确保每次进入页面都是新的开始
    this.dictationManager.resetState();
    
    // 添加状态变化监听器
    this.stateChangeListener = this.onDictationStateChange.bind(this);
    this.dictationManager.addListener(this.stateChangeListener);
    
    // 加载发音设置
    this.dictationManager.loadPronunciationSettings();
    
    // 检查是否从复习页面进入
    if (options.fromReviewMagic && options.fromReviewMagic === 'true') {
      this.dictationManager.loadReviewWords();
    } else {
      this.dictationManager.loadBooksAndGroups();
    }
  },
  
  onShow: function() {
    // 如果页面重新显示，确保状态同步
    const state = this.dictationManager.getState();
    this.setData({
      isLoading: state.isLoading,
      isDictating: state.isDictating,
      isSelectingSource: state.isSelectingSource,
      showDictationResult: state.showDictationResult
    });
  },
  
  /**
   * 监听DictationManager状态变化，更新页面级UI状态
   */
  onDictationStateChange: function(state) {
    // 只更新页面级的主要状态，用于控制组件显示/隐藏
    this.setData({
      isLoading: state.isLoading,
      isDictating: state.isDictating,
      isSelectingSource: state.isSelectingSource,
      showDictationResult: state.showDictationResult
    });
  },
  
  /**
   * 返回上一页
   */
  goBack: function() {
    wx.navigateBack();
  },
  
  /**
   * 页面卸载时清理资源
   */
  onUnload: function() {
    // 停止音频播放
    this.dictationManager.stopPronunciation();
    
    // 移除状态变化监听器
    if (this.stateChangeListener) {
      this.dictationManager.removeListener(this.stateChangeListener);
    }
    
    // 清理DictationManager资源
    this.dictationManager.cleanup();
  },
  
  // 转发给朋友
  onShareAppMessage: function() {
    return {
      title: '拾刻学习 - 单词听写挑战',
      path: '/pages/challenge/word-dictation/word-dictation',
      // imageUrl: '/images/write.png'
    };
  },
  
  // 分享到朋友圈
  onShareTimeline: function() {
    return {
      title: '拾刻学习 - 单词听写挑战',
      query: 'from=timeline',
      // imageUrl: '/images/write.png'
    };
  }
});